package org.example.c_0_003;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Phaser;

/**
 * 可以有多重栅栏，用来统一线程运行的各个阶段。
 */
public class T_Phaser {
    MyPhaser myPhaser = new MyPhaser(7);

    class MyPhaser extends Phaser{
        public MyPhaser(int parties) {
            super(parties);
        }

        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            switch (phase){
                case 0:
                    System.out.println("全员到齐！");
                    return false;
                case 1:
                    System.out.println("吃饭结束！");
                    return false;
                case 2:
                    System.out.println("全员解散！");
                    return false;
                case 3:
                    System.out.println("送入洞房！");
                    return true;
                default:
                    return true;
            }
        }
    }

    @Test
    public void run(){
        new Person("新郎").start();
        new Person("新娘").start();
        new Person("t" + 0).start();
        new Person("t" + 1).start();
        new Person("t" + 2).start();
        new Person("t" + 3).start();
        new Person("t" + 4).start();
        try {
            Thread.sleep(3000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    class Person extends Thread{
        private String personName;

        public Person(String personName) {
            this.personName = personName;
        }

        public void ready(){
            System.out.println(personName+"就绪");
            myPhaser.arriveAndAwaitAdvance();
        }

        public void eat(){
            System.out.println(personName+"吃饭");
            myPhaser.arriveAndAwaitAdvance();
        }

        public void out(){
            System.out.println(personName+"离开");
            myPhaser.arriveAndAwaitAdvance();
        }

        public void makeBoy(){
            if (personName.equals("新郎")||personName.equals("新娘")){
                System.out.println(personName+"洞房");
                myPhaser.arriveAndAwaitAdvance();
            }else {
                myPhaser.arriveAndDeregister();
            }
        }

        @Override
        public void run() {
            ready();
            eat();
            out();
            makeBoy();
        }
    }
}
